package com.fujin.gulimall.search.service.Impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.fujin.common.Vo.SkuEsModel;
import com.fujin.common.utils.R;
import com.fujin.gulimall.search.Vo.AttrResponseVo;
import com.fujin.gulimall.search.Vo.BrandVo;
import com.fujin.gulimall.search.Vo.SearchParam;
import com.fujin.gulimall.search.Vo.SearchResult;
import com.fujin.gulimall.search.config.ElasticSearchConfig;
import com.fujin.gulimall.search.constant.EsConstant;
import com.fujin.gulimall.search.feign.ProductFeign;
import com.fujin.gulimall.search.service.mallSearchService;
import org.apache.lucene.search.join.ScoreMode;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.*;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.nested.NestedAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.nested.ParsedNested;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedLongTerms;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @title: mallSearchServiceImpl
 * @Author Tan
 * @Date: 2022/2/17 14:25
 * @Version 1.0
 */
@Service
public class mallSearchServiceImpl implements mallSearchService {

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @Autowired
    private ProductFeign productFeign;

    @Override
    public SearchResult search(SearchParam searchParam) {   //根据带来的请求内容封装
        SearchResult searchResult= null;
        // 通过请求参数构建查询请求
        SearchRequest searchRequest = bulidSearchRequest(searchParam);

        try {
            //发送检索请求
            SearchResponse searchResponse = restHighLevelClient.search(searchRequest, ElasticSearchConfig.COMMON_OPTIONS);

            // 将es响应数据封装成结果
            searchResult = bulidSearchResult(searchParam,searchResponse);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return searchResult;
    }

    /**
     * 通过请求参数构建查询请求
     * @param searchParam
     * @return
     */
    private SearchRequest bulidSearchRequest(SearchParam searchParam) {
        //用于构建DSL语句
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        /**
         * 1、构建一个模糊查询
         */
        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();

        //1.1、must模糊匹配
        if (!StringUtils.isEmpty(searchParam.getKeyword())){
            boolQueryBuilder.must(QueryBuilders.matchQuery("skuTitle",searchParam.getKeyword()));
        }

        //1.2、过滤(按照属性、分类、品牌、价格区间、库存)
        //bool - filter - 按照三级分类id查询
        if (searchParam.getCatalog3Id() != null){
            boolQueryBuilder.filter(QueryBuilders.termQuery("catalogId",searchParam.getCatalog3Id()));
        }

        //bool - filter - 按照品牌id查询
        if (searchParam.getBrandId() != null && searchParam.getBrandId().size() > 0){
            boolQueryBuilder.filter(QueryBuilders.termsQuery("brandId",searchParam.getBrandId()));
        }

        //bool - filter - 按照是否有货进行查询
        if (searchParam.getHasStock() != null) {
            boolQueryBuilder.filter(QueryBuilders.termQuery("hasStock", searchParam.getHasStock() == 1));
        }

        //bool - filter - 按照价格区间查询
        if (!StringUtils.isEmpty(searchParam.getSkuPrice())){
            //构建查询区间
            RangeQueryBuilder skuPrice = QueryBuilders.rangeQuery("skuPrice");
            //传入的价格区间格式:0_500(0-500)、_500(最大500)、500_(从五百开始)
            //根据"_"进行分割
            String[] s = searchParam.getSkuPrice().split("_");
            if (s.length == 2){
                skuPrice.gte(s[0]);
                skuPrice.lte(s[1]);
            }else if (s.length == 1){
                if (searchParam.getSkuPrice().startsWith("_")){
                    skuPrice.lte(s[0]);
                }
                if (searchParam.getSkuPrice().endsWith("_")){
                    skuPrice.gte(s[0]);
                }
            }
            boolQueryBuilder.filter(skuPrice);
        }

        //bool - filter - 按照attr属性进行查询
        List<String> attrs = searchParam.getAttrs();
        if (attrs!=null && attrs.size() > 0){
            //传入的属性格式attrs=1_5寸:8寸&2_16G:8G
            for (String attrStr : attrs) {
                BoolQueryBuilder nestedQueryBuilder = new BoolQueryBuilder();

                String[] attr = attrStr.split("_"); //根据"_"取出数据
                String attId = attr[0]; //检索的属性id
                String[] attrValues = attr[1].split(":");   //检索的属性值

                nestedQueryBuilder.must(QueryBuilders.termQuery("attrs.attrId",attId));
                nestedQueryBuilder.must(QueryBuilders.termsQuery("attrs.attrValue", attrValues));

                NestedQueryBuilder nestedQuery = QueryBuilders.nestedQuery("attrs", nestedQueryBuilder, ScoreMode.None);
                boolQueryBuilder.filter(nestedQuery);
            }
        }

        //将构建好的条件和过滤进行查询
        sourceBuilder.query(boolQueryBuilder);

        /**
         * 2、排序、分页、高亮展示
         */
        //2.1、排序
        if (!StringUtils.isEmpty(searchParam.getSort())){
            //格式:saleCount_desc/asc
            String[] s = searchParam.getSort().split("_");
            SortOrder sortMode = s[1].equalsIgnoreCase("asc")?SortOrder.ASC:SortOrder.DESC;
            sourceBuilder.sort(s[0],sortMode);
        }
        //2.2、分页
        sourceBuilder.from((searchParam.getPageNum() - 1) * EsConstant.PRODUCT_PAGESIZE);
        sourceBuilder.size(EsConstant.PRODUCT_PAGESIZE);

        //2.3、高亮展示
        //Keyword不为空的时候才需要高亮
        if (!StringUtils.isEmpty(searchParam.getKeyword())){
            HighlightBuilder highlightBuilder = new HighlightBuilder();
            highlightBuilder.field("skuTitle");
            highlightBuilder.preTags("<b style='color:red'>");
            highlightBuilder.postTags("</b>");
            sourceBuilder.highlighter(highlightBuilder);
        }

        /**
         * 3、聚合
         */
        //3.1、品牌聚合
        TermsAggregationBuilder brandAgg = AggregationBuilders.terms("brandAgg");
        brandAgg.field("brandId").size(50);

        //品牌子聚合
        brandAgg.subAggregation(AggregationBuilders.terms("brandNameAgg").field("brandName").size(1));
        brandAgg.subAggregation(AggregationBuilders.terms("brandImgAgg").field("brandImg").size(1));
        sourceBuilder.aggregation(brandAgg);

        //3.2、分类聚合
        TermsAggregationBuilder catalogAgg = AggregationBuilders.terms("catalogAgg").field("catalogId").size(30);
        //分类子聚合
        catalogAgg.subAggregation(AggregationBuilders.terms("catalogNameAgg").field("catalogName").size(1));
        sourceBuilder.aggregation(catalogAgg);

        //3.3、属性聚合
        //nested最外层聚合
        NestedAggregationBuilder nested = AggregationBuilders.nested("attr_agg", "attrs");
        //attrIdAgg为nested的子聚合
        TermsAggregationBuilder attrIdAgg = AggregationBuilders.terms("attrIdAgg").field("attrs.attrId").size(10);

        //attr_name_agg为attrIdAgg的子聚合
        attrIdAgg.subAggregation(AggregationBuilders.terms("attr_name_agg").field("attrs.attrName").size(50));
        //attr_value_agg为attrIdAgg的子聚合
        attrIdAgg.subAggregation(AggregationBuilders.terms("attr_value_agg").field("attrs.attrValue").size(50));

        //添加子聚合
        nested.subAggregation(attrIdAgg);
        sourceBuilder.aggregation(nested);

        String s = sourceBuilder.toString();
        System.out.println(s);

        SearchRequest request  = new SearchRequest(new String[]{EsConstant.PRODUCT_INDEX},sourceBuilder);

        return request;
    }

    /**
     * 将es响应数据封装成结果
     * @param searchParam
     * @param searchResponse
     * @return
     */
    private SearchResult bulidSearchResult(SearchParam searchParam, SearchResponse searchResponse) {
        SearchResult result = new SearchResult();

        //1、封装商品信息
        SearchHits hits = searchResponse.getHits();
        List<SkuEsModel> skuEsModels = new ArrayList<>();
        if (hits!=null && hits.getHits().length > 0) {
            for (SearchHit hit : hits.getHits()) {
                String source = hit.getSourceAsString();
                SkuEsModel esModel = JSON.parseObject(source, SkuEsModel.class);
                skuEsModels.add(esModel);
            }
        }
        result.setProducts(skuEsModels);

        //2、封装属性信息
        List<SearchResult.AttrVo> attrVoList = new ArrayList<>();
        ParsedNested attrAgg = searchResponse.getAggregations().get("attr_agg");
        ParsedLongTerms attrIdAgg = attrAgg.getAggregations().get("attrIdAgg");
        for (Terms.Bucket bucket : attrIdAgg.getBuckets()) {
            SearchResult.AttrVo attrVo = new SearchResult.AttrVo();

            //1、获取属性id
            long attrId = bucket.getKeyAsNumber().longValue();
            long attrId1 = bucket.getKeyAsNumber().longValue();
            //该属性用于标记属性是否被面包屑导航选中
            attrVo.setAttrId(attrId1);
            //2、获取属性名称
            String attrName = ((ParsedStringTerms) bucket.getAggregations().get("attr_name_agg")).getBuckets().get(0).getKeyAsString();
            //2、获取属性值
            ParsedStringTerms attr_value_agg = bucket.getAggregations().get("attr_value_agg");
            //属性值可能存在多个值所以需要遍历,并转为List<String>集合
            List<String> attrValue = attr_value_agg.getBuckets().stream().map(item -> {
                String keyAsString = ((Terms.Bucket) item).getKeyAsString();
                return keyAsString;
            }).collect(Collectors.toList());

            attrVo.setAttrId(attrId);
            attrVo.setAttrName(attrName);
            attrVo.setAttrValue(attrValue);
            attrVoList.add(attrVo);
        }

        result.setAttrs(attrVoList);

        //3、封装品牌信息
        List<SearchResult.BrandVo> brandVoList = new ArrayList<>();
        ParsedLongTerms brandAgg = searchResponse.getAggregations().get("brandAgg");
        List<? extends Terms.Bucket> buckets = brandAgg.getBuckets();
        for (Terms.Bucket bucket : buckets) {
            SearchResult.BrandVo brandVo = new SearchResult.BrandVo();
            //bucket的key就是品牌id
            Long branId = bucket.getKeyAsNumber().longValue();
            brandVo.setBrandId(branId);

            //在子聚合中得到品牌名称
            ParsedStringTerms brandNameAgg = bucket.getAggregations().get("brandNameAgg");
            String brandName = brandNameAgg.getBuckets().get(0).getKeyAsString();
            brandVo.setBrandName(brandName);

            //在子聚合中得到品牌图片
            ParsedStringTerms brandImgAgg = bucket.getAggregations().get("brandImgAgg");
            if (brandImgAgg!=null && brandImgAgg.getBuckets().size() > 0) {
                String brandImg = brandImgAgg.getBuckets().get(0).getKeyAsString();
                brandVo.setBrandImg(brandImg);
            }
            brandVoList.add(brandVo);
        }
        result.setBrands(brandVoList);

        //4、封装分类信息
        List<SearchResult.CatalogVo> catalogVoList = new ArrayList<>();
        ParsedLongTerms catalogAgg = searchResponse.getAggregations().get("catalogAgg");
        List<? extends Terms.Bucket> catalogAggBuckets = catalogAgg.getBuckets();
        for (Terms.Bucket catalogAggBucket : catalogAggBuckets) {
            SearchResult.CatalogVo catalogVo = new SearchResult.CatalogVo();
            //获取cataLogId
            String catalogId = catalogAggBucket.getKeyAsString();
            catalogVo.setCatalogId(Long.parseLong(catalogId));

            //在子聚合中获取分类名称
            ParsedStringTerms aggregations = catalogAggBucket.getAggregations().get("catalogNameAgg");
            String CataLogName = aggregations.getBuckets().get(0).getKeyAsString();
            catalogVo.setCatalogName(CataLogName);
            catalogVoList.add(catalogVo);
        }
        result.setCatalogs(catalogVoList);

        //5、封装分页信息
        //5.1、设置页码
        result.setPageNum(searchParam.getPageNum());
        //5.2、设置总记录数
        long total = hits.getTotalHits().value;
        result.setTotal(total);
        //5.3、设置总页码     总记录 % 每页展示条数 == 0？总记录 / 每页展示条数：()总记录 / 每页展示条数 + 1
        result.setTotalPages((int)total % EsConstant.PRODUCT_PAGESIZE==0?(int)total/EsConstant.PRODUCT_PAGESIZE:(int)total / EsConstant.PRODUCT_PAGESIZE+1);

        //可遍历的页码
        List<Integer> pageNavs = new ArrayList<>();
        for (int i = 1; i <= result.getTotalPages(); i++) {
            pageNavs.add(i);
        }
        result.setPageNavs(pageNavs);

        //6、面包屑属性导航值设置
        if (searchParam.getAttrs() != null && searchParam.getAttrs().size() > 0) {
            searchParam.getAttrs().stream().map(item -> {
                SearchResult.NavVo navVo = new SearchResult.NavVo();
                //属性格式 attrs=1_5寸:8寸
                String[] s = item.split("_");
                navVo.setNavValue(s[1]);

                //根据attrId远程调用商品服务通过attrId获取attr信息
                R info = productFeign.info(Long.parseLong(s[0]));
                if (info.getCode() == 0) {
                    //调用成功
                    AttrResponseVo attr = info.getData("attr", new TypeReference<AttrResponseVo>() {
                    });
                    navVo.setName(attr.getAttrName());
                } else {
                    //调用失败直接使用attrId
                    navVo.setName(s[0]);
                }

                //取消某个面包屑 将要跳转到那个地方 将请求地址中url里面对应的属性置空
                //得到所有查询条件，去掉当前
                String replace = replaceQueryString(searchParam, item,"attrs");
                navVo.setName("http://localhost:14000/list.html?" + replace);

                return navVo;
            }).collect(Collectors.toList());
        }

        //7、面包屑品牌导航值设置
        if (searchParam.getBrandId() != null && searchParam.getBrandId().size() > 0 ){
            List<SearchResult.NavVo> navs = result.getNavs();
            SearchResult.NavVo navVo = new SearchResult.NavVo();
            navVo.setName("品牌");

            //远程查询所有品牌
            R infos = productFeign.infos(searchParam.getBrandId());
            if (infos.getCode() == 0){
                //调用成功
                List<BrandVo> brand = infos.getData("brand", new TypeReference<List<BrandVo>>() {
                });

                StringBuffer buffer = new StringBuffer();
                String replace = null;
                for (BrandVo brandVo : brand) {
                    buffer.append(brandVo.getBrandName()+"");
                    //得到所有查询条件，去掉当前
                    replace = replaceQueryString(searchParam, brandVo.getBrandId()+"","brandId");
                }
                navVo.setNavValue(buffer.toString());
                navVo.setLink("http://search.gulimail.com/list.html?"+replace);
            }
            navs.add(navVo);
            result.setNavs(navs);
        }

        return result;
    }

    /**
     * 浏览器和java编码转换
     * @param param
     * @param value
     * @param key
     * @return
     */
    private String replaceQueryString(SearchParam param, String value, String key) {
        String encode = null;
        try {
            encode = URLEncoder.encode(value, "UTF-8");
            //浏览器将空格变为"+",而java是变为%20，所以需要替换
            encode = encode.replace("+", "%20");//浏览器和java对+号的差异化处理
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        String replace = param.get_queryString().replace("&"+key+"=" + encode, "");
        return replace;
    }

}
